import 'package:flower/components/custom_toast.dart';
import 'package:flower/model/coupon_model.dart';
import 'package:flutter/foundation.dart';

import '../config/service_url.dart';
import '../model/cart_list.dart';
import '../utils/http_util.dart';

/* 购物车状态 */
class CartModel with ChangeNotifier, DiagnosticableTreeMixin {
  // 购物车所有商品
  Map<int, CartData> allCartFlower = <int, CartData>{};

  // 购物车选中的商品
  Map<int, CartData> checkCartFlower = <int, CartData>{};

  // 选择商品的价格总和
  double totalPrice = 0;

  // 可用优惠券
  List<CouponData> availableCoupons = [];

  // 已选择的优惠券
  CouponData? selectedCoupon;

  // 优惠额度
  double couponPrice = 0;

  // 初始化购物车商品数据到状态管理中
  void setCartListData(List<CartData> cartListData) {
    for (var cart in cartListData) {
      allCartFlower[cart.fid] = cart;
      checkCartFlower[cart.fid] = cart;
    }
    notifyListeners();
  }

  // 设置商品选择是否选择的状态
  void setCartItemStatus(int fid) {
    if (checkCartFlower[fid] != null) {
      checkCartFlower.remove(fid);
    } else {
      checkCartFlower[fid] = allCartFlower[fid]!;
    }
    notifyListeners();
  }

  // 点击全选或者反选
  void setAllStatus() {
    if (checkCartFlower.length == allCartFlower.length) {
      checkCartFlower.clear();
    } else {
      checkCartFlower = Map.from(allCartFlower);
    }
    notifyListeners();
  }

  // 获取全选或者反选状态显示
  bool getAllStatus() {
    return checkCartFlower.length == allCartFlower.length;
  }

  // 判断购物车中商品前面的图标是否被选择
  bool getFlowerIsCheck(int fid) {
    return checkCartFlower[fid] != null;
  }

  // 获取所有商品
  List<CartData> getAllFlower() {
    List<CartData> list = [];
    allCartFlower.forEach((key, value) {
      list.add(value);
    });
    return list;
  }

  // 获取所有购物车Id
  List<int> getAllCartId() {
    List<int> list = [];
    checkCartFlower.forEach((key, value) {
      list.add(value.id);
    });
    return list;
  }

  // 获取选择中的商品
  List<CartData> getCheckFlower() {
    List<CartData> list = [];
    checkCartFlower.forEach((key, value) {
      list.add(value);
    });
    return list;
  }

  // 计算所选中的商品的价格
  double getFlowerAllPrice() {
    totalPrice = 0;
    checkCartFlower.forEach((key, value) {
      // 商品价格总和
      totalPrice += value.amount;
    });

    return totalPrice;
  }

  // 获取各种计算后的价格
  double getDiscountPrice() {
    totalPrice = 0;
    checkCartFlower.forEach((key, value) {
      // 商品价格总和
      totalPrice += value.amount;
    });

    // 如果有选择优惠券，计算折扣后的总价
    if (selectedCoupon != null && totalPrice >= selectedCoupon!.threshold) {
      totalPrice -= couponPrice;
    }
    return totalPrice;
  }

  // 商品数量减1
  void decrementQuantity(int fid) async {
    if (allCartFlower.containsKey(fid)) {
      CartData cartItem = allCartFlower[fid]!;
      if (cartItem.number > 1) {
        cartItem.number--;
        // 更新总价
        cartItem.amount = cartItem.number * cartItem.price;
        // 修改数据库
        Map<String, dynamic> map = <String, dynamic>{};
        map["fid"] = fid;
        map["number"] = cartItem.number;
        map["amount"] = cartItem.amount;

        await HttpUtil.post(updateCartItemNumber, queryParameters: map);
      } else {
        // 数量小于1时，直接删除购物车项
        allCartFlower.remove(fid);
        checkCartFlower.remove(fid);
        // 修改数据库
        Map<String, dynamic> map = <String, dynamic>{};
        map["fid"] = fid;

        await HttpUtil.post(deleteFromCart, queryParameters: map);
      }
      notifyListeners();
    }
  }

  // 商品数量加一
  void incrementQuantity(int fid) async {
    if (allCartFlower.containsKey(fid)) {
      CartData cartItem = allCartFlower[fid]!;
      cartItem.number++;
      cartItem.amount = cartItem.number * cartItem.price;
      // 修改数据库
      Map<String, dynamic> map = <String, dynamic>{};
      map["fid"] = fid;
      map["number"] = cartItem.number;
      map["amount"] = cartItem.amount;

      await HttpUtil.post(updateCartItemNumber, queryParameters: map);
      notifyListeners();
    }
  }

  // 删除购物车项
  void removeItem(int fid) async {
    allCartFlower.remove(fid);
    checkCartFlower.remove(fid);
    // 修改数据库
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = fid;

    await HttpUtil.post(deleteFromCart, queryParameters: map);
    notifyListeners();
  }

    // 删除已选中的购物车项
  void removeSelectedItems() async {
    for (int fid in checkCartFlower.keys.toList()) {
      allCartFlower.remove(fid);
      checkCartFlower.remove(fid);
      // 修改数据库
      Map<String, dynamic> map = <String, dynamic>{};
      map["fid"] = fid;

      await HttpUtil.post(deleteFromCart, queryParameters: map);
    }
    notifyListeners();
  }

  // 设置可用的优惠券
  void setAvailableCoupons(List<CouponData> coupons) {
    availableCoupons = coupons;
    notifyListeners();
  }

  // 选择优惠券
  void selectCoupon(int couponId) {
    selectedCoupon =
        availableCoupons.firstWhere((coupon) => coupon.id == couponId);
    // 要判断优惠券是否符合条件
    if (selectedCoupon!.threshold > totalPrice) {
      CustomToast.showWarningToast("这张卷不符合使用条件o~~~");
      return;
    }
    // 要判断优惠券的价格是否大于总额度
    couponPrice = totalPrice < selectedCoupon!.discount
        ? totalPrice
        : selectedCoupon!.discount;
    notifyListeners();
  }

  // 取消选择优惠券
  void deselectCoupon() {
    selectedCoupon = null;
    couponPrice = 0;
    notifyListeners();
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<Map<int, CartData>>(
        'allCartFlower', allCartFlower));
    properties.add(DiagnosticsProperty<Map<int, CartData>>(
        'checkCartFlower', checkCartFlower));
    properties.add(DoubleProperty('totalPrice', totalPrice));
    properties.add(
        IterableProperty<CouponData>('availableCoupons', availableCoupons));
    properties.add(
        DiagnosticsProperty<CouponData?>('selectedCoupon', selectedCoupon));
  }
}
